<template>
    <div>
        <div class="option">
            <el-button plain @click="cancel">取消</el-button>
            <div class="button-group" data-aos="fade-up" data-aos-delay="70" @click="doSubmit">
                <Button title="选好了" size="small" icon="arrow-right"/>
            </div>
        </div>

        <div class="uploaders">
            <el-upload
                    :action="this.$global.apiUrl+'file/uploadImg?userId='+uid"
                    list-type="picture-card"
                    :on-success="handleSuccess"
                    :on-change="handleChange"
                    accept="image/jpeg,image/png,image/tiff,image/tif"
                    :file-list="fileList"
                    :before-upload="checkFileType"
                    multiple>
                <i slot="default" class="el-icon-plus"></i>
                <div slot="file"
                     v-loading="file.loading"
                     slot-scope="{file}" :class="{'checked':file.checked}"  style="height: 100%;">
                    <img
                            class="el-upload-list__item-thumbnail"
                            :src="file.url" alt="" >
<!--                    <thumbnail :file="file" ></thumbnail>-->
                    <span class="el-upload-list__item-actions">
                        <span
                                class="el-upload-list__item-preview"
                                @click="handlePictureCardPreview(file)">
                                <el-tooltip content="放大" placement="top">
                                    <i class="el-icon-zoom-in"></i>
                                </el-tooltip>
                        </span>
                        <span
                                class="el-upload-list__item-delete"
                                @click="checkPic(file)">
                                <el-tooltip content="选择" placement="top">
                                    <i class="el-icon-crop"></i>
                                </el-tooltip>

                        </span>
                        <span
                                class="el-upload-list__item-delete"
                                @click="handleRemove(file)">
                                <el-tooltip content="删除" placement="top">
                                    <i class="el-icon-delete"></i>
                                </el-tooltip>
                        </span>
                    </span>
                </div>
                <div slot="tip" class="el-upload__tip">请上传图片格式文件</div>
            </el-upload>
            <el-dialog :visible.sync="dialogVisible" :modal="false">
                <img width="100%" :src="dialogImageUrl" alt="" >

            </el-dialog>
        </div>
    </div>

</template>

<script>
    import eventBus from "../../global/eventBus";
    import Button from "../elements/button/Button";
    import thumbnail from "./thumbnail";
    import Tiff from 'tiff.js';
    export default {
        name: "PhotoUploader",
        components: {Button,thumbnail},
        props: {
        },
        data() {
            return {
                uid:this.$ls.get('userInfo')===null?'':this.$ls.get('userInfo').id,
                // fullscreenLoading: false,//加载状态
                dialogImageUrl: '', //应该是大图预览
                dialogVisible: false,
                fileList: [],
                // riff: 0,
                // notriff:1,
            }
        },

        mounted() {
            if(this.$ls.get('userInfo')!==null){
                this.getUserImgList()
            }
        },
        methods: {
            checkFileType (file) {
                const fileName = file.name
                const fileType = fileName.substring(fileName.lastIndexOf('.'))
                // jpeg,.png,.jpg,.bmp,.gif
                if (
                    fileType === '.jpg' ||
                    fileType === '.png' ||
                    fileType === '.jpeg' ||
                    fileType === '.bmp' ||
                    fileType === '.gif' ||
                    fileType === '.tif' ||
                    fileType === '.tiff'
                ) {

                } else {
                    this.$message.error(
                        '请上传正确的图片类型'
                    )
                    return false
                }
            },
            //获得文件列表
            getUserImgList(){
                var that = this
                this.$axios.get(this.$global.apiUrl+'library/getAll?userId='+this.uid)
                .then(function (response) {
                    // console.log(response.data.data)
                    const resData = response.data.data
                    resData.forEach(function (item) {
                        const file = {};
                        if (item.name.indexOf(".tif")!==-1||item.name.indexOf(".tiff")!==-1) {
                            console.log('有一张tif')
                            try {
                                var xhr = new XMLHttpRequest();
                                xhr.responseType = 'arraybuffer';
                                xhr.open('GET', item.file);
                                xhr.onload = (e) => {
                                    var tiff = new Tiff({buffer: xhr.response});
                                    var canvas = tiff.toCanvas();
                                    file.url = canvas.toDataURL();
                                    file.id=item.id
                                    file.name = item.name
                                    file.url4req = item.file
                                    file.checked=false
                                    file.loading=false
                                    that.fileList.push(file)
                                };
                                xhr.send();
                            } catch (e) {
                                // this.src = this.file.url;
                            }
                        }else{
                            file.url = item.file
                            file.id=item.id
                            file.name = item.name
                            file.url4req = item.file
                            file.checked=false
                            file.loading=false
                            that.fileList.push(file)
                        }
                        // file.id=item.id
                        // file.name = item.name
                        // file.url4req = item.file
                        // file.checked=false
                        // file.loading=false
                        // that.fileList.push(file)
                    })
                }).catch(function (error) {
                    console.log(error)
                })
            },
            //删除图片
            handleRemove(file) {
                // console.log(file, fileList);
                // console.log('在删除')
                // console.log(file.id)
                var that = this
                var index = this.fileList.indexOf(file)
                if(index>-1){
                    this.fileList.splice(index,1)
                    this.$axios.post(this.$global.apiUrl+'library/removeOne?id='+file.id)
                        .then(function (response) {

                        }).catch(function (error) {
                        that.$message.error('网络错误，稍后再试');
                    })
                }
            },

            handlePictureCardPreview(file) {
                this.dialogImageUrl = file.url;
                this.dialogVisible = true;
            },
            handleSuccess(res,file,fileList) {
                // console.log(file.name)
                // console.log('在handleSuccess')
                if(res.code===200){
                    try {
                        var type = res.data.substring(res.data.lastIndexOf('.'))
                        if (type==='.tif'||type==='.tiff') {
                            var xhr = new XMLHttpRequest();
                            xhr.responseType = 'arraybuffer';
                            xhr.open('GET', res.data);
                            xhr.onload = (e) => {
                                var tiff = new Tiff({ buffer: xhr.response });
                                var canvas = tiff.toCanvas();
                                file.url = canvas.toDataURL();
                            };
                            xhr.send();
                        } else {
                            file.url=res.data
                        }
                        file.url4req=res.data
                        file.id = res.message
                        file.checked=false
                    }catch (e) {
                        this.$message.error('网络错误，稍后再试')
                    }
                }
            },
            // 会根据图片名称查重
            handleChange(file, fileList) {
                // let existFile = fileList.slice(0, fileList.length - 1).find(f => f.name === file.name);
                // if (existFile) {
                //     this.$message.error('当前文件已经存在!');
                //     fileList.pop();
                // }
                file.loading=!file.loading
                // console.log('在handleChange上传')
                if(file.loading){
                    var type = file.name.substring(file.name.lastIndexOf('.'))
                    if (type==='.tif'||type==='.tiff') {
                        try {
                            var xhr = new XMLHttpRequest();
                            xhr.responseType = 'arraybuffer';
                            xhr.open('GET', file.url);
                            xhr.onload = (e) => {
                                var tiff = new Tiff({ buffer: xhr.response });
                                var canvas = tiff.toCanvas();
                                file.url = canvas.toDataURL();
                            };
                            xhr.send();
                        }catch (e) {
                            // this.src = this.file.url;
                        }
                    }
                }
                this.fileList = fileList;
            },
            checkPic(file){
                // console.log(file)
                file.checked=!file.checked
                this.$forceUpdate()
                // console.log('在选择')
            },
            cancel(){
                document.documentElement.style.overflowY = 'auto'
                this.fileList.forEach(item=>{
                    item.checked=false
                })
                this.$emit('doSubmit') //让drawer能够在选中图片后收起
            },
            doSubmit() {
                document.documentElement.style.overflowY = 'auto'
                var list=[]
                this.fileList.forEach(item=>{
                    if(item.checked){
                        list.push(item)
                    }
                })
                if(list.length>0){
                    eventBus.$emit('repo2wks',list) //将选中的图片放入框内
                }
                this.cancel()
            }
        }
    }
</script>

<style scoped>
    .checked{
        /*选中的样式*/
        border: #E33FA1 solid 5px;
    }
    .uploaders {
        /*width: 500px;*/
        display: flex;
        flex-direction: row;
        margin-left: 30px;
        margin-top: 15px;
        /*justify-content: space-around;*/
    }
    .option{
        display: flex;
        flex-direction: row;
        margin-left: 30px;
        margin-right: 30px;
        justify-content: space-between;
    }

</style>
